package com.cloudfun.campusshare.device.protocol.decoder;

import com.cloudfun.campusshare.device.protocol.command.PumpFrame;
import com.cloudfun.campusshare.device.protocol.constant.PumpWorkStatus;
import com.cloudfun.campusshare.device.protocol.response.*;
import com.cloudfun.campusshare.util.ByteUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/5/19 9:48
 **/
@Slf4j
public class PumpDecoder {
    public static BaseMessage decode(PumpFrame frame){
        log.info("液体泵收到消息为{}",frame.toString());
        byte cmdType = frame.getCmdType();
        byte[] data = frame.getData();
        switch (cmdType){
            case 1:
                // 0 空闲状态 1 正在工作 2 故障
            case 2:
                // 0 未启动 1 开始工作
            case 6:
                // 0 未启动 1 延迟工作
                AllPumpStatus allPumpStatus = AllPumpStatus.build();
                allPumpStatus.clear();
                for (int i = 0; i < 3; i++) {
                    allPumpStatus.add(new PumpStatus(i+1,cmdType, PumpWorkStatus.getPumpStatus(cmdType,data[i])));
                }
                return allPumpStatus;
            case 3:
            case 4:
            case 5:
                // 1 抽液结束 2 抽液泵不工作
                AllPumpStatus pumpStatus = AllPumpStatus.build();
                pumpStatus.clear();
                // 命令3对应1号泵 命令4对应2号泵 命令5对应3号泵
                pumpStatus.add(new PumpStatus(cmdType - 2,cmdType,PumpWorkStatus.getPumpStatus(cmdType,data[0])));
                return pumpStatus;
            case 7:
                // 工作时间 延迟时间 ...(工作时间占用1字节 延迟时间占用2个字节,一共3个泵，共9字节)
                if(data.length != 9){
                    log.error("命令{}回复数据格式不对{}",cmdType,data);
                    break;
                }
                AllPumpWorkInfo allPumpWorkInfo = AllPumpWorkInfo.build();
                allPumpWorkInfo.clear();
                for (int i = 0; i <= 6; i = i + 3) {
                    allPumpWorkInfo.add(new PumpWorkInfo((i+1) / 2,data[i],getDelayTime(data,i + 1,i + 3)));
                }
                return allPumpWorkInfo;
            default:
                log.error("没有找到对应指令{}",cmdType);
                break;
        }
        return null;
    }

    private static int getDelayTime(byte[] data, int start, int end){
        byte[] subarray = ArrayUtils.subarray(data, start, end);
        return ByteUtil.byteArrayToInt(subarray);
    }

}
